package cn.my.framework.config.security;

import cn.my.framework.common.service.UserPermService;
import cn.my.framework.util.ConstantData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * Created by zhangl_lc on 2017/7/7.
 */
@Component("mySecurityMetadataSource")
public class MyInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

    Logger logger = LoggerFactory.getLogger(MyInvocationSecurityMetadataSource.class);

    @Autowired
    UserPermService permService;

    private static Map<String, Collection<ConfigAttribute>> permMap = new HashMap<>();

    @PostConstruct
    public void init(){
        logger.debug("----- init the perm role map-----");
        permMap.clear();
        List<Map<String,String>> prList = permService.listMenuPermsWithRole();
        for(Map<String,String> pr : prList){
            String url = pr.get("url");
            Collection<ConfigAttribute> rs = permMap.get(url);
            if(rs == null){
                rs = new ArrayList<>();
                permMap.put(url,rs);
            }
            rs.add(new SecurityConfig(pr.get("roleCode")));
        }
    }

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        if(ConstantData.securityEnable){
             HttpServletRequest request = ((FilterInvocation) object).getHttpRequest();
            AntPathRequestMatcher matcher;
            for(String url : permMap.keySet()){
                matcher = new AntPathRequestMatcher(url);
                if(matcher.matches(request)){
                    return permMap.get(url);
                }
            }
        }
        return null;
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }
}
